package org.redtroy.theater.dao.hibernate;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.redtroy.theater.bean.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component(value = "abstractHiberate4DAO")
public abstract class AbstractHiberate4DAO<T> {
	@Autowired
	@Qualifier(value = "sessionFactory")
	private SessionFactory sessionFactory;

	public T persist(T o) {
		getCurrentSession().persist(o);
		return o;
	}

	@SuppressWarnings("unchecked")
	public org.redtroy.theater.bean.Pager<T> retrievePageByCriteria(int pageNo,
			int pageSize, Criteria criteria) {
		long rows = (Long) criteria.setProjection(
				Projections.countDistinct(Projections.id().toString()))
				.uniqueResult();
		criteria.setProjection(null);
		criteria.setResultTransformer(Criteria.ROOT_ENTITY);
		criteria.setFirstResult((pageNo - 1) * pageSize);
		criteria.setMaxResults(pageSize);
		List<T> result = criteria.list();
		return new Pager<T>(pageNo, pageSize, rows, result);
	}

	public Criteria createCriteria() {
		return getCurrentSession().createCriteria(getActualClass());
	}

	private Session getCurrentSession() {
		return getSessionFactory().getCurrentSession();
	}

	public Serializable save(T o) {
		return getCurrentSession().save(o);
	}

	@SuppressWarnings("unchecked")
	public T retrieve(Serializable id) {
		return (T) getCurrentSession().load(getActualClass(), id);
	}

	@SuppressWarnings("unchecked")
	public T get(Serializable id) {
		return (T) getCurrentSession().get(getActualClass(), id);
	}

	@SuppressWarnings("unchecked")
	public T load(Serializable id) {
		return (T) getCurrentSession().load(getActualClass(), id);
	}

	@SuppressWarnings("unchecked")
	public T merge(T o) {
		return (T) getCurrentSession().merge(o);
	}

	public void update(T o) {
		getCurrentSession().update(o);
	}

	public void delete(T o) {
		getCurrentSession().delete(o);
	}

	public int deleteByHQL(Query query) {
		return query.executeUpdate();
	}

	public int updateByHQL(Query query) {
		return query.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public List<T> listAll() {
		return getCurrentSession().createCriteria(getActualClass()).list();
	}

	@SuppressWarnings("unchecked")
	private Class<T> getActualClass() {
		return (Class<T>) ((ParameterizedType) (getClass()
				.getGenericSuperclass())).getActualTypeArguments()[0];
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
